import sys
import sqlite3
from datetime import datetime
from models import Board, Post

def find_parent_post(post, parent_id):
    query=Post.gql("WHERE pid = :1", parent_id)
    if query.count()>0:
        post.parent_post=query.get()
    else:
        print("parent post is not found. {0}".format(parent_id))

# Read / Write
query=Board.gql('ORDER BY bid')
boards=query.fetch(1000)
for board in boards:
    print( board.name )

# read sqlite3
conn=sqlite3.connect('RedFoxForum.db')
c=conn.cursor()
board_result_set=c.execute("select * from board")
for row in board_result_set:
    print(">>>" + str(row[0]))
    board=Board.get_or_insert(str(row[0]))
    board.bid=row[0]
    board.name=row[1]
    board.put()

# CREATE TABLE post (id integer, parentid integer, boardid integer, ishead boolean, title text, content text, author text, posted datetime);
post_result_set=c.execute("select * from post")
posts=[]
count=0
for row in post_result_set:
    count=count+1
    print(">>>" + str(row[0]))
    post=Post.get_or_insert(str(row[0]))
    board=Board.gql("WHERE bid = :1", row[2])
    post.board=board[0]
    ishead=row[3]
    if ishead==1:
        post.parent_post=None
    else:
        find_parent_post(post, row[1])
    post.title=row[4]
    post.content=row[5]
    post.author=row[6]
    post.posted=datetime.strptime(row[7], "%Y-%m-%d %H:%M:%S")
    posts.append(post)
    if count%50==0:
        db.put(posts)
        posts=[]
        print('flush')

print(count)
conn.close()
